package com.daylightrobbery.server.packet.login;

import com.daylightrobbery.entity.Account;
import com.daylightrobbery.server.GameManager;
import com.daylightrobbery.server.entity.DeviceInfo;
import com.daylightrobbery.server.packet.type.DataPacket;
import com.daylightrobbery.service.AccountService;
import com.daylightrobbery.service.UserSignInLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class LoginUdpServerReqPacket implements DataPacket {

    private int type = 10001;
    private String uid;
    private String account;
    private String password;
    private DeviceInfo deviceInfo;

    AccountService accountService = GameManager.Instance.accountService;

    UserSignInLogService userSignInLogService  = GameManager.Instance.userSignInLogService;

    public String getUid() {
        return uid;
    }

    public LoginUdpServerReqPacket setUid(String uid) {
        this.uid = uid;
        return this;
    }

    public String getAccount() {
        return account;
    }

    public LoginUdpServerReqPacket setAccount(String account) {
        this.account = account;
        return this;
    }

    public String getPassword() {
        return password;
    }

    public LoginUdpServerReqPacket setPassword(String password) {
        this.password = password;
        return this;
    }

    @Override
    public String toString() {
        return "LoginUdpServerPacket{" +
                "type=" + type +
                ", uid='" + uid + '\'' +
                ", account='" + account + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    @Override
    public DataPacket process() {
        LoginUdpServerRespPacket resp = new LoginUdpServerRespPacket();

        Account accountInDB = accountService.checkUserAndGetInfo(new Account()
        .setAccount(account)
        .setPassword(password));
        if(accountInDB != null){
            resp.setMsg(LoginUdpServerRespPacket.SUCCESS);
        }else{
            resp.setMsg(LoginUdpServerRespPacket.ERROR);
            return resp;
        }
        if(resp.getMsg().equals(LoginUdpServerRespPacket.SUCCESS)){
            resp.setAccount(this.account);
            resp.setUid(accountInDB.getUid());
            //resp.setUid(UUID.randomUUID().toString().substring(0, 8));
            GameManager.getInstance().addUserOnline(
                    resp.getUid(),
                    accountInDB);


        }
        return resp;
    }

    public DeviceInfo getDeviceInfo() {
        return deviceInfo;
    }

    public LoginUdpServerReqPacket setDeviceInfo(DeviceInfo deviceInfo) {
        this.deviceInfo = deviceInfo;
        return this;
    }

    @Override
    public int getType() {
        return type;
    }
}
